using Newtonsoft.Json.Serialization;
using XchUserInfo.BLL;
using XchUserInfo.Common;
using XchUserInfo.DAL;
using System;
using System.IO;
using System.Linq;
namespace XchUserInfo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            // ע���������CORS������
            const string MyCorsPolicy = "MyCorsPolicy";
            builder.Services.AddCors(options =>
            {
                options.AddPolicy(name: MyCorsPolicy,
                policy =>
                {
                    policy.AllowAnyOrigin();
                    policy.AllowAnyHeader();
                    policy.AllowAnyMethod();
                });
            });
            // ע��������� JSON ���л�����
            builder.Services.AddControllers().AddNewtonsoftJson(options =>
            {
                // ����������ƴ�Сд��һ������
                options.SerializerSettings.ContractResolver = new
               DefaultContractResolver();
            });
            // �����Զ� 400 ��Ӧ
            builder.Services.AddControllers().ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter = true;
            });
            // ע�� DI ����������ע�����
            builder.Services.BatchRegisterServices();
            builder.Services.AddHttpContextAccessor();
            var app = builder.Build();
            // ���� HTTP ����ܵ�
            app.UseHttpsRedirection();
            app.UseStaticFiles(); // ���þ�̬�ļ�֧��
            app.UseCors(MyCorsPolicy); // ���� CORS
            app.UseAuthorization();
            app.MapControllers();
            // 初始化数据库（如未创建表则创建并灌入示例数据）
            using (var scope = app.Services.CreateScope())
            {
                var factory = scope.ServiceProvider.GetService<IConnectionFactory>();
                if (factory != null)
                {
                    using var conn = factory.GetConnection();
                    conn.Open();
                    var candidates = new[]
                    {
                        Path.Combine(AppContext.BaseDirectory, "XchUserInfo.Data", "sql", "XchUserInfo.sql"),
                        Path.Combine(Directory.GetCurrentDirectory(), "XchUserInfo.Data", "sql", "XchUserInfo.sql")
                    };
                    var sqlPath = candidates.FirstOrDefault(File.Exists);
                    if (sqlPath != null)
                    {
                        var script = File.ReadAllText(sqlPath);
                        using var cmd = conn.CreateCommand();
                        cmd.CommandText = script;
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            app.Run();
        }
    }
}